#!/bin/bash

# 确保脚本在错误时停止
set -e

echo "开始离线部署Todo应用..."

# 生成随机密钥
if grep -q "your_secret_key_here" docker-compose.yml; then
    SECRET_KEY=$(openssl rand -hex 16)
    echo "生成的密钥: $SECRET_KEY"
    sed -i "s/your_secret_key_here/$SECRET_KEY/g" docker-compose.yml
fi

# 创建一个临时的后端Dockerfile，不依赖Docker Hub
cat > backend/Dockerfile.offline <<EOF
FROM ubuntu:20.04

# 设置非交互式安装
ENV DEBIAN_FRONTEND=noninteractive

# 安装Python和依赖
RUN apt-get update && apt-get install -y python3 python3-pip python3-venv && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app

# 创建并激活虚拟环境
RUN python3 -m venv /venv
ENV PATH="/venv/bin:$PATH"

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
RUN pip install gunicorn

COPY . .

# 设置环境变量
ENV FLASK_APP=app.py
ENV FLASK_ENV=production

# 暴露端口
EXPOSE 8080

# 启动命令
CMD ["gunicorn", "--bind", "0.0.0.0:8080", "app:app"]
EOF

# 创建一个临时的前端Dockerfile，不依赖Docker Hub
cat > frontend/Dockerfile.offline <<EOF
FROM ubuntu:20.04

# 设置非交互式安装
ENV DEBIAN_FRONTEND=noninteractive

# 安装Node.js和Nginx
RUN apt-get update && apt-get install -y curl gnupg nginx && \
    curl -fsSL https://deb.nodesource.com/setup_18.x | bash - && \
    apt-get install -y nodejs && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app

# 配置npm使用淘宝镜像
RUN npm config set registry https://registry.npmmirror.com

COPY package*.json ./
RUN npm install

COPY . .
RUN npm run build

# 配置Nginx
COPY nginx.conf /etc/nginx/conf.d/default.conf
RUN rm /etc/nginx/sites-enabled/default
RUN mkdir -p /usr/share/nginx/html
RUN cp -r dist/* /usr/share/nginx/html/

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]
EOF

# 创建一个临时的docker-compose文件
cat > docker-compose.offline.yml <<EOF
version: '3.8'

services:
  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile.offline
    container_name: todo-backend
    restart: always
    volumes:
      - ./backend/todos.db:/app/todos.db
    environment:
      - FLASK_APP=app.py
      - FLASK_ENV=production
      - SECRET_KEY=$SECRET_KEY
    networks:
      - app-network

  frontend:
    build:
      context: ./frontend
      dockerfile: Dockerfile.offline
    container_name: todo-frontend
    restart: always
    ports:
      - "80:80"
    depends_on:
      - backend
    networks:
      - app-network

networks:
  app-network:
    driver: bridge
EOF

# 增加超时时间
export DOCKER_CLIENT_TIMEOUT=300
export COMPOSE_HTTP_TIMEOUT=300

# 构建并启动容器
echo "构建并启动Docker容器..."
docker-compose -f docker-compose.offline.yml up -d --build

echo "部署完成！应用现在应该在http://localhost或您的服务器IP上运行"
